package com.mumulx.check.controller;

import com.mumulx.check.redis.entity.PartTestBoxed;
import com.mumulx.check.server.ExecuteChecker;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/*
 *  Created by IntelliJ IDEA.
 *  User: 木木
 *  Date: 2020/10/28
 *  Time: 21:10
 */
//@RestController = @Controller + @ResponseBody组成,
// @RestController注解Controller，则Controller中的方法无法返回jsp页面，
//返回结果为json数据
@RestController
public class RemoteServerCotroller {
    @Resource
    ExecuteChecker executeChecker;

    @PostMapping("/remoteserver/executechecker")
    public int executechecker(@RequestParam("partTestBoxed") PartTestBoxed partTestBoxed) {

        //int rs = executeChecker.execute(partTestBoxed.getParts(), partTestBoxed.getRules(), null);
        return -1;
    }
    //用于服务熔断
    @HystrixCommand(fallbackMethod = "getHystrix")//指定备选方法
    @GetMapping("/remoteserver/test/{id}")
    public int test(@PathVariable("id") int id) {
        return new Random().nextInt(20);
    }

    //备选方法
    public int getHystrix(@PathVariable("id") int id){

        return -2;
    }

    //获取一些配置信息，得到具体的微服务
    @Autowired
    private DiscoveryClient client;
    @GetMapping("/dept/discovery")
    //注册进来的微服务，获取一些信息
    public Object discovery() {
        //获得微服务列表的清单
        List<String> services = client.getServices();
        System.out.println("discovery=>services" + services);

        //得到一个具体的微服务信息
        List<ServiceInstance> instance = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        for (ServiceInstance serviceInstance : instance) {
            System.out.println(
                    serviceInstance.getHost()+"\t"+
                            serviceInstance.getPort()+"\t"+
                            serviceInstance.getUri()+"\t"+
                            serviceInstance.getServiceId()
            );
        }
        return  this.client;
    }

}
